"""

用户管理
"""
from django.contrib.auth.hashers import check_password, make_password
from django.core.validators import RegexValidator
from django.forms import PasswordInput
from django.shortcuts import render, redirect, get_object_or_404
from django.core.exceptions import ValidationError
from django import forms
from workDjango import models
from workDjango.models import UserData
# from workDjango.utils.encrypt import md5
from workDjango.utils import BootStrapModelForm, BootStrapForm
from workDjango.utils.encrypt import md5


class UserManagerModelForm(BootStrapModelForm.ManagerModelForm):
    username = forms.CharField(
        label="用户名",
        widget=forms.TextInput(attrs={"class": "form-control"}),
        validators=[RegexValidator(r'^[0-9a-zA-Z]{8,20}$', '用户名格式不正确')],
        error_messages={
            'required': '用户名不能为空',
        }
    )

    password = forms.CharField(
        label="密码",
        widget=forms.PasswordInput(attrs={"class": "form-control"}),
        validators=[RegexValidator(r'^[0-9a-zA-Z]{8,20}$', '密码格式不正确')],
        error_messages={
            'required': '密码不能为空',
        }
    )
    password2 = forms.CharField(
        label="确认密码",
        widget=forms.PasswordInput  # 隐藏显示
    )

    class Meta:
        model = models.UserData
        fields = ["username", "password"]
        widgets = {
            "password": forms.PasswordInput()
        }

    def clean_password(self):
        pwd = self.cleaned_data.get('password')
        pwd = md5(pwd)
        return pwd

    def clean_password2(self):
        pwd = self.cleaned_data.get('password')
        pwd2 = md5(self.cleaned_data.get('password2'))
        # pwd2 = self.cleaned_data.get('password2')
        print(pwd,pwd2)
        if pwd != pwd2:
            raise ValidationError('两次密码不一致')
        return pwd2


# 用户创建
def user_create(request):
    if request.method == "GET":
        form = UserManagerModelForm()
        return render(request, 'user_create.html', {"form": form})
    form = UserManagerModelForm(data=request.POST)
    if form.is_valid():
        # 验证通过
        # 1.获取用户输入的密码
        pwd = form.cleaned_data.get('password')
        name = form.cleaned_data.get('username')
        # 2.对密码进行加密
        # pwd = md5(pwd)
        # 3.保存到数据库
        form.instance.password = pwd
        form.instance.name = name
        form.save()
        return redirect('/system/login')
    return render(request, 'user_create.html', {"form": form})


# 用户详情页面
def user_detail(request):
    return render(request, 'user_detail.html')


# 用户信息，密码修改
class UserUpdateModelForm(BootStrapModelForm.ManagerModelForm):
    old_password = forms.CharField(
        label="原密码",
        widget=forms.PasswordInput(attrs={"class": "form-control"}),
        validators=[RegexValidator(r'^[0-9a-zA-Z]{8,20}$', '密码格式不正确')],
        error_messages={
            'required': '密码不能为空',
        }
    )
    password = forms.CharField(
        label="新密码",
        widget=forms.PasswordInput(attrs={"class": "form-control"}),
        validators=[RegexValidator(r'^[0-9a-zA-Z]{8,20}$', '密码格式不正确')],
        error_messages={
            'required': '密码不能为空',
        }
    )
    password2 = forms.CharField(
        label="确认密码",
        widget=PasswordInput(attrs={"class": "form-control"}),
        error_messages={
            'required': '密码不能为空',
        }
        # widget=forms.PasswordInput  # 隐藏显示
    )

    class Meta:
        model = models.UserData
        fields = ["name"]

    def clean_old_password(self):
        old_pwd = md5(self.cleaned_data.get('old_password'))
        user = self.instance
        if old_pwd != user.password:
            # if not check_password(old_pwd, user.password):
            #     print(old_pwd)
            #     print(user.password)
            raise ValidationError(f'原密码错误')
        return md5(old_pwd)

    def clean_password(self):
        pwd = self.cleaned_data.get('password')
        return md5(pwd)

    def clean_password2(self):
        pwd = self.cleaned_data.get('password')
        pwd2 = md5(self.cleaned_data.get('password2'))
        print(pwd, pwd2)
        if pwd and pwd2 and pwd != pwd2:
            raise ValidationError('两次密码不一致')
        return pwd2


def user_update(request, id):
    user_obj = get_object_or_404(UserData, id=id)

    if request.method == "GET":
        form = UserUpdateModelForm(instance=user_obj)
        return render(request, 'user_update.html', {"form": form})

    form = UserUpdateModelForm(data=request.POST, instance=user_obj)
    # print(request.POST)

    if form.is_valid():
        form.instance.password = form.cleaned_data.get('password')
        # print(form.instance.password)
        form.save()
        return redirect('/system/login')  # 或者重定向到其他页面
    else:
        return render(request, 'user_update.html', {"form": form})

# 实例
# def user_update(request, id):
#     user_obj = models.UserData.objects.filter(id=id).first()
#     # print(user_obj)
#     if request.method == "GET":
#         form = UserUpdateModelForm(instance=user_obj)
#         return render(request, 'user_update.html', {"form": form})
#     form = UserUpdateModelForm(data=request.POST, instance=user_obj)
#     print(request.POST)
#     print(form.is_valid())
#     if form.is_valid():
#         # 验证通过
#         # 1.获取用户输入的密码
#         name = form.cleaned_data.get('username')
#         pwd = form.cleaned_data.get('password')
#         old_pwd = form.cleaned_data.get('old_password')
#         # print(name, pwd, old_pwd)
#         if old_pwd != user_obj.password:
#             form.add_error('old_password', '原密码错误')
#             return render(request, 'user_update.html', {"form": form})
#         # 2.对密码进行加密
#         # pwd = md5(pwd)
#         # 3.保存到数据库
#         else:
#             form.instance.name = name
#             form.instance.password = pwd
#             form.save()
#     else:
#         # print(form.errors)
#         return render(request, 'user_update.html', {"form": form})
#     return redirect('/system/login')
